from wtforms import Form, StringField, validators, ValidationError, IntegerField
from app.models import UserModel


class AccountEdit(Form):
    id = StringField(validators=[validators.DataRequired(message='id 为空')])
    name = StringField(validators=[validators.DataRequired(message='用户昵称为空')])
    username = StringField(validators=[validators.DataRequired(message='用户账号为空')])
    sort = IntegerField(validators=[validators.NumberRange(min=0, max=None, message='排序为空')])
    roles_ids = StringField(validators=[validators.DataRequired(message='身份为空')])

    def validate_username(self, field):
        old_model = UserModel.query.get(self.id.data)
        new_model = UserModel.query.filter_by(username=field.data).first()
        # 可以是当前 id 的 username，但是不允许是其他数据库字段的 username
        if new_model and not old_model.username == field.data:
            raise ValidationError('账号已存在，请重新输入账号')


class AccountAdd(Form):
    name = StringField(validators=[validators.DataRequired(message='用户昵称为空')])
    username = StringField(validators=[validators.DataRequired(message='用户账号为空')])
    sort = IntegerField(validators=[validators.NumberRange(min=0, max=None, message='排序为空')])
    roles_ids = StringField(validators=[validators.DataRequired(message='身份为空')])

    def validate_username(self, field):
        user_model = UserModel.query.filter_by(username=field.data).first()
        if user_model:
            raise ValidationError('账号已存在，请重新输入账号')
